# $Id: Filter.pm,v 1.5 2004/06/21 12:12:30 ibo Exp $

package CGI::FOGE2::Filter;
use strict;
use CGI::FOGE2::Form;
use CGI::FOGE2::Tools;

our @ISA = ();

sub new {
    my $proto = shift;
    my $class = ref($proto) || $proto;
    my %args = @_;

    my $self = {
        form => $args{form},
	structure => undef,
    };
    bless $self, $class;
    $self->{structure} = $self->parse_filter();
    return $self;
}

sub setform {
    my $self = shift;
    my ($form) = @_;
    $self->{form} = $form;
}

sub create_temp_table {
    my $self = shift;
    my $form = $self->{form};
    my $table = $form->{dbAnswer};

    return unless (keys %{$self->{structure}});
    
    my $db = $form->dbh_r();
    my $query = "CREATE TEMP TABLE $table AS\n";
    $query .= $self->as_sql();

    print STDERR $query;

    $db->do($query) || CGI::Carp::croak($DBI::errstr);    
}

sub parse_filter {
    my $self = shift;
    my $form = $self->{form};
    my %structure = ();

    foreach my $sec (@{$form->{sections}}) {
	my $secname = $sec->get_table_name();
	foreach my $q (@{$sec->{questions}}) {
	    my $qname = $q->generate_field_names()->[0];
	    next unless defined CGI::param($qname);
	    foreach my $val (CGI::param($qname)) {
		my $bof = $form->get_bof();
		chomp $val;
		next if $val =~ /^$/;
		next if $val =~ /^\s+$/;
		next if $val =~ /$bof/;
		push @{$structure{$secname}->{$qname}}, $val;
	    }
	}
    }
    return \%structure;
}

sub as_text {
    my $self = shift;
    my $s = $self->{structure};
    my $out = '';
    foreach my $sec (keys %$s) {
	$out .= CGI::h1($sec);
	foreach my $q (keys %{$s->{$sec}}) {
	    $out .= CGI::h2($q);
	    $out .= CGI::h3($s->{$sec}{$q});
	}
    }
    return $out;
}

sub as_hidden {
    my $self = shift;
    my $s = $self->{structure};
    my $out = '';

    foreach my $sec (keys %$s) {
	foreach my $q (keys %{$s->{$sec}}) {
	    my @vals = ();
	    foreach my $val (@{$s->{$sec}{$q}}) {
		push @vals, $val;
#$out .= CGI::hidden(-name => $q, -value => $val);
	    }
	    $out .= CGI::hidden($q, @vals);
	}
    }

    $out .= CGI::hidden(-name => 'configfilter') if keys %$s;
    return $out;    
}

sub as_sql {
    my $self = shift;
    my $form = $self->{form};
    my $s = $self->{structure};

    my $select = "$form->{dbAnswer}.*";
    my $from = "$form->{dbAnswer}";
    my @where = ();
    
    my $last_sec = $form->{dbAnswer};

    my $out = '';

    foreach my $sec (keys %$s) {
	$from .= ", $sec";
	push @where, "${last_sec}.id = ${sec}.id";
	$last_sec = $sec;
	foreach my $q (keys %{$s->{$sec}}) {
	    my @ors = ();
	    foreach my $val (@{$s->{$sec}{$q}}) {
		$val =~ s/\'/\\\'/;
		push @ors, "${sec}.${q} like \'%$val%\'";
	    }
	    push @where, ' ( ' . (join ' OR ', @ors) . ' ) ';
	}
    }
    $out = 'SELECT ' . $select . "\n";
    $out .= 'FROM ' . $from . "\n";
    $out .= 'WHERE ' . (join ' AND ', @where) . "\n";

    return $out;
}

1;

# end of FormStats.pm
